package com.ruoyi.wifiauth.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.wifiauth.api.AdvertisementClient;
import com.ruoyi.wifiauth.config.WifiStrategyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 策略服务
 * 实现容错和缓存机制
 * 
 * @author ruoyi
 */
@Service
public class StrategyService {
    
    private static final Logger log = LoggerFactory.getLogger(StrategyService.class);
    
    private static final String STRATEGY_CACHE_KEY = "wifi:strategy:device:";
    
    @Autowired
    private AdvertisementClient advertisementClient;
    
    @Autowired
    private RedisService redisService;
    
    @Autowired
    private WifiStrategyConfig wifiStrategyConfig;
    
    /**
     * 获取设备策略（带缓存和容错）
     * 
     * @param deviceId 设备ID
     * @return 策略数据
     */
    public AjaxResult getStrategyByDevice(String deviceId) {
        try {
            // 1. 尝试从缓存获取
            if (wifiStrategyConfig.isCacheEnabled()) {
                String cacheKey = STRATEGY_CACHE_KEY + deviceId;
                String cachedStrategy = redisService.getCacheObject(cacheKey);
                
                if (cachedStrategy != null) {
                    log.debug("从缓存获取设备策略: deviceId={}", deviceId);
                    Map<String, Object> strategyData = JSONObject.parseObject(cachedStrategy);
                    return AjaxResult.success(strategyData);
                }
            }
            
            // 2. 调用广告服务获取策略
            AjaxResult result = callAdvertisementService(deviceId);
            
            if (result != null && result.isSuccess()) {
                // 调用成功，缓存结果
                if (wifiStrategyConfig.isCacheEnabled()) {
                    String cacheKey = STRATEGY_CACHE_KEY + deviceId;
                    redisService.setCacheObject(cacheKey,
                            JSONObject.toJSONString(result.get(AjaxResult.DATA_TAG)),
                        (long) wifiStrategyConfig.getCacheTtl(), 
                        TimeUnit.SECONDS);
                }
                
                log.info("成功获取设备策略: deviceId={}", deviceId);
                return result;
            } else {
                // 调用失败，返回默认策略
                log.warn("调用广告服务失败，返回默认策略: deviceId={}", deviceId);
                return getDefaultStrategy(deviceId);
            }
            
        } catch (Exception e) {
            log.error("获取设备策略异常，返回默认策略: deviceId={}", deviceId, e);
            return getDefaultStrategy(deviceId);
        }
    }
    
    /**
     * 调用广告服务
     * 
     * @param deviceId 设备ID
     * @return 调用结果
     */
    private AjaxResult callAdvertisementService(String deviceId) {
        try {
            log.debug("调用广告服务获取策略: deviceId={}", deviceId);
            return advertisementClient.getStrategyByDevice(deviceId);
        } catch (Exception e) {
            log.error("调用广告服务异常: deviceId={}", deviceId, e);
            return null;
        }
    }
    
    /**
     * 获取默认策略
     * 
     * @param deviceId 设备ID
     * @return 默认策略
     */
    private AjaxResult getDefaultStrategy(String deviceId) {
        try {
            WifiStrategyConfig.DefaultStrategyConfig defaultConfig = wifiStrategyConfig.getDefault();
            
            Map<String, Object> strategy = new HashMap<>();
            strategy.put("strategyId", defaultConfig.getStrategyId());
            strategy.put("strategyName", defaultConfig.getStrategyName());
            strategy.put("advertisementCount", defaultConfig.getAdvertisementCount());
            strategy.put("durationSeconds", defaultConfig.getDurationSeconds());
            strategy.put("deviceId", deviceId);
            strategy.put("isDefault", true);
            
            // 转换素材数据
            List<Map<String, Object>> materials = new ArrayList<>();
            if (defaultConfig.getMaterials() != null) {
                for (WifiStrategyConfig.DefaultMaterial material : defaultConfig.getMaterials()) {
                    Map<String, Object> materialMap = new HashMap<>();
                    materialMap.put("materialId", material.getMaterialId());
                    materialMap.put("materialName", material.getMaterialName());
                    materialMap.put("materialType", material.getMaterialType());
                    materialMap.put("materialUrl", material.getMaterialUrl());
                    materialMap.put("durationSeconds", material.getDurationSeconds());
                    materials.add(materialMap);
                }
            }
            strategy.put("materials", materials);
            
            log.info("返回默认策略: deviceId={}, materialCount={}", deviceId, materials.size());
            
            return AjaxResult.success(strategy);
            
        } catch (Exception e) {
            log.error("生成默认策略失败: deviceId={}", deviceId, e);
            
            // 最小化默认策略
            Map<String, Object> minimalStrategy = new HashMap<>();
            minimalStrategy.put("strategyId", "0");
            minimalStrategy.put("strategyName", "默认策略");
            minimalStrategy.put("advertisementCount", 1);
            minimalStrategy.put("durationSeconds", 5);
            minimalStrategy.put("deviceId", deviceId);
            minimalStrategy.put("isDefault", true);
            minimalStrategy.put("materials", new ArrayList<>());
            
            return AjaxResult.success(minimalStrategy);
        }
    }
    
    /**
     * 清除设备策略缓存
     * 
     * @param deviceId 设备ID
     */
    public void clearStrategyCache(String deviceId) {
        if (wifiStrategyConfig.isCacheEnabled()) {
            String cacheKey = STRATEGY_CACHE_KEY + deviceId;
            redisService.deleteObject(cacheKey);
            log.info("清除设备策略缓存: deviceId={}", deviceId);
        }
    }
    
    /**
     * 清除所有策略缓存
     */
    public void clearAllStrategyCache() {
        if (wifiStrategyConfig.isCacheEnabled()) {
            String pattern = STRATEGY_CACHE_KEY + "*";
            redisService.deleteObject(redisService.keys(pattern));
            log.info("清除所有策略缓存");
        }
    }
    
    /**
     * 预热策略缓存
     * 
     * @param deviceId 设备ID
     */
    public void warmupStrategyCache(String deviceId) {
        try {
            log.info("预热策略缓存: deviceId={}", deviceId);
            getStrategyByDevice(deviceId);
        } catch (Exception e) {
            log.error("预热策略缓存失败: deviceId={}", deviceId, e);
        }
    }
} 